dojo.require("esri.tasks.locator");
dojo.require("esri.toolbars.navigation");
dojo.require("esri.virtualearth.VETiledLayer");
dojo.require("esri.virtualearth.VEGeocoder");

var map,
	tiledMapServiceLayer,
  	labelMapServiceLayer,
  	veTileLayer,
  	veGeocoder,
  	navToolbar,
  	mapLoading;

var bingKey = 'AnUFxJX8NNRS82SDk5960nGRWnwNnHa-zFL56Vcdai4dQAM0UlODBymbn3kmXhAQ';
var currentCulture = '';
var language = '';

var createTravellingAnimalsMap = function () {
	if(navigator.userLanguage) language = navigator.userLanguage.substr(0,2).toLowerCase();
	else language = navigator.language.substr(0,2).toLowerCase();
	
	switch(language) {
		case 'fr':
			currentCulture = 'fr-FR';
			break;
		case 'en':
			currentCulture = 'en-US';
			break;
		case 'es':
			currentCulture = 'es-ES';
			break;
		default:
			currentCulture = 'en-US';
	}
	
	var initialExtent = new esri.geometry.Extent({"xmin": -16545674,"ymin":-7265760,"xmax":18676509,"ymax": 16215695,"spatialReference":{"wkid":102100}});
    
    map = new esri.Map("map", {
		extent: initialExtent, 
		fadeOnZoom:true,
		force3DTransforms:true,
		logo: false,
		navigationMode: 'css-transforms'
		});
    
    map.hidePanArrows();
    map.hideZoomSlider();
    map.enablePan();
    
    locatorService = new esri.tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
    dojo.connect(locatorService, "onLocationToAddressComplete", onAdresseComplete);
    
    map.infoWindow.resize(150,100);
    
    navToolbar = new esri.toolbars.Navigation(map);

	dojo.connect(map, "onZoomStart", showMapLoading);
	dojo.connect(map, "onPanStart", showMapLoading);
	
	dojo.connect(map, "onLoad", function() {
		showMapLoading();
	});

	manageBasemap();
	
	veGeocoder = new esri.virtualearth.VEGeocoder({
		 bingMapsKey: bingKey,
		 culture: currentCulture
	});
	
	dojo.connect(tiledMapServiceLayer, "onUpdate", hideMapLoading);
	dojo.connect(labelMapServiceLayer, "onUpdate", hideMapLoading);
	dojo.connect(veTileLayer, "onUpdate", hideMapLoading);
	
	$("#radioset_navigation").buttonset();
	$("#radioset_fdp").buttonset();
	
	$("#radio_zoom").button({icons: {primary: "ui-icon-zoomin"}, text: false});
	$("#radio_dezoom").button({icons: {primary: "ui-icon-zoomout"}, text: false});
	$("#radio_pan").button({icons: {primary: "ui-icon-arrow-4"}, text: false});
	$("#button_locate").button({icons: {primary: "ui-icon-search"}, text: false});
	
	$("#radioset_navigation").change(onNavigationToolChanged);
	$("#radioset_fdp").change(manageBasemap);
	
	$("#input_locate").keypress(onInputLocateKeyPress);
	$("#button_locate").click(onInputLocate);
    
    return map;
}

var newPoint = function(x, y) {
	return new esri.geometry.Point(x, y, new esri.SpatialReference({ wkid: 4326 }));
}

var newMultipoint = function() {
	return new esri.geometry.Multipoint(new esri.SpatialReference({ wkid: 4326 }));
}

var zoomToPoint = function(map, point) {
	map.centerAndZoom(point, 10);
};

var zoomToPoints = function(map, multipoint) {
	if(multipoint.points.length == 1) {
		zoomToPoint(map, multipoint.getPoint(0));
	} else {
		map.setExtent(multipoint.getExtent().expand(2));
	}
};

function getPositionGraphic(x, y, first) {
	var point = newPoint(x, y);
	var symbol;
	if(first) {
		symbol = new esri.symbol.PictureMarkerSymbol({"angle":0,"xoffset":12,"yoffset":12,"type":"esriPMS","url":"http://static.arcgis.com/images/Symbols/Transportation/CheckeredFlag.png","contentType":"image/png","width":24,"height":24});
	} else {
		symbol = new esri.symbol.PictureMarkerSymbol({"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS","url":"http://static.arcgis.com/images/Symbols/Basic/OrangeSphere.png","contentType":"image/png","width":24,"height":24});
	}
	return new esri.Graphic(point, symbol);
}

function getAddVisitGraphic(x, y, adresse) {
	var point = newPoint(x, y);
	var symbol;
	if(adresse) {
		symbol = new esri.symbol.PictureMarkerSymbol({"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS","url":"http://static.arcgis.com/images/Symbols/Basic/RedSphere.png","contentType":"image/png","width":24,"height":24});
	} else {
		symbol = new esri.symbol.PictureMarkerSymbol({"angle":0,"xoffset":0,"yoffset":0,"type":"esriPMS","url":"http://static.arcgis.com/images/Symbols/Basic/OrangeSphere.png","contentType":"image/png","width":24,"height":24});
	}
	return new esri.Graphic(point, symbol);
}

function getLineGraphic(x1, y1, x2, y2) {
	var polylineJson = {
			  "paths":[[[x1, y1], [x2, y2]]],
			  "spatialReference":{"wkid":4326}
			};
	var polyline = new esri.geometry.Polyline(polylineJson);
	var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,255,0]), 0.5);
	return new esri.Graphic(polyline, symbol);
}

function onNavigationToolChanged() {
	switch($("#radioset_navigation :radio:checked").attr('id')) {
		case "radio_pan":
			navToolbar.activate(esri.toolbars.Navigation.PAN);
			break;
		case "radio_zoom":
			navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
			break;
		case "radio_dezoom":
			navToolbar.activate(esri.toolbars.Navigation.ZOOM_OUT);
			break;
	}
}

function manageBasemap() {	
	if(veTileLayer != null) {
		map.removeLayer(veTileLayer);
	}

	if(tiledMapServiceLayer != null) {
		map.removeLayer(tiledMapServiceLayer);
	}
	
	if(labelMapServiceLayer != null) {
		map.removeLayer(labelMapServiceLayer);
	}
	
	switch($("#radioset_fdp :radio:checked").attr('id')) {
		case "radio_leger":
			tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer");
			labelMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer");

			map.addLayer(tiledMapServiceLayer, 0);
			map.addLayer(labelMapServiceLayer, 1);
			break;
		case "radio_aerien":
			veTileLayer = new esri.virtualearth.VETiledLayer({
		        bingMapsKey: bingKey,
		        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL,
		        culture: currentCulture
		      });
			map.addLayer(veTileLayer, 0);
			break;
		case "radio_plan":
			veTileLayer = new esri.virtualearth.VETiledLayer({
		        bingMapsKey: bingKey,
		        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_ROAD,
		        culture: currentCulture
		      });
			map.addLayer(veTileLayer, 0);
			break;
		case "radio_mixte":
			veTileLayer = new esri.virtualearth.VETiledLayer({
		        bingMapsKey: bingKey,
		        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL_WITH_LABELS,
		        culture: currentCulture
		      });
			map.addLayer(veTileLayer, 0);
			break;
	}
}

function showMapLoading() {
	esri.show(mapLoading);
}

function hideMapLoading() {
	layersLoaded++;
	if (layersLoaded === map.layerIds.length) {
		esri.hide(mapLoading);
		layersLoaded = 0;
	}
}

function onInputLocateKeyPress(event) {
	var keycode = (event.keyCode ? event.keyCode : event.which);
	if(keycode == '13'){
		onInputLocate();
	}
}

function onInputLocate() {
	var query = $("#input_locate").val();
	
	veGeocoder.addressToLocations(query, onVEGeocoderSuccess);
}

function onVEGeocoderSuccess(geocodeResults) {
	map.setExtent(esri.geometry.geographicToWebMercator(geocodeResults[0].bestView));
}

